const resolveApp = require('./paths');

const HtmlWebpackPlugin = require('html-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const TerserPlugin = require('terser-webpack-plugin');

const { merge } = require('webpack-merge');

const prodConfig = require('./webpack.prod');
const devConfig = require('./webpack.dev');

const commonConfig = {
  // watch: true,
  mode: "development",
  entry: {
    main: {
      import: "./src/main.js", 
      dependOn: "shared"
    },
    index: {
      import: "./src/index.js", 
      dependOn: "shared"
    },
    shared: ["lodash", "dayjs"]
  },
  output: {
    filename: "[name].bundle.js",
    path: resolveApp("./build"),
    chunkFilename: "[name].[hash:6].chunk.js"
    // publicPath: './'
    // publicPath: '/abc'
  },
  resolve: {
    extensions: [".wasm", ".mjs", ".js", ".json", ".jsx", ".ts", ".vue"],
    alias: {
      "@": resolveApp("./src"),
      "pages": resolveApp("./src/pages")
    }
  },
  optimization: {
    minimizer: [
      new TerserPlugin({
        extractComments: false
      })
    ],
    // natural:自然数(不推荐)
    // named:使用包所在目录作为name(在开发环境推荐)
    // deterministic:生成id，针对相同文件生成的id是不变
    chunkIds: "deterministic", // webpack的id生成算法
    splitChunks: {
      // async异步导入
      // initial同步导入
      // all 异步/同步导入
      chunks: "all",
      // 最小尺寸: 如果拆分出来一个，拆分出来的包的大小最小为minSize
      minSize: 20000,
      // 将大于maxSize的包，拆分成不小于minSize的包
      maxSize: 20000,
      // minChunks表示引入的包，至少被导入几次
      minChunks: 1,
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          filename: "[id]_vendors.js",
          priority: -10
        },
        // bar: {
        //   test: /bar_/,
        //   filename: "[id]_bar.js"
        // },
        default: {
          minChunks: 2,
          filename: "common_[id].js",
          priority: -20
        }
      }
    },
    // true/multiple
    // single
    runtimeChunk: {
      // name: "runtime-yz"
      name: function(entrypoint) {
        return `yz-${entrypoint.name}`
      }
    }
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/i,
        use: "babel-loader"
      },
      {
        test: /\.vue$/i,
        use: "vue-loader"
      },
      {
        test: /\.css/i,
        use: [
          "style-loader",
          "css-loader"
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./index.html"
    }),
    new VueLoaderPlugin()
  ]
}
module.exports = function(env) {
  const isProduction = env.production;
  process.env.production = isProduction;
  return isProduction ? merge(commonConfig, prodConfig) : merge(commonConfig, devConfig)
}